package timing.ukulele.form.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import timing.ukulele.form.persistent.EntityConfig;
import timing.ukulele.common.Constant;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.form.service.EntityConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/entityConfig")
@Api(tags = "实体模板配置")
@Slf4j
public class EntityConfigController {

    final EntityConfigService service;

    public EntityConfigController(EntityConfigService service) {
        this.service = service;
    }

    @GetMapping
    public ResponseResult<EntityConfig> getById(@RequestParam("id") Long id) {
        return ResponseResult.success(service.getById(id));
    }

    @PostMapping("/save")
    public ResponseResult<EntityConfig> saveHolidayConfig(
            @RequestBody EntityConfig config,
            @ApiParam(value = "系统权限ID") @RequestHeader(Constant.SYSTEM) String authSystem) {
        if (config == null || StringUtils.isEmpty(config.getSystemId()))
            return ResponseResult.error("参数不完整");
        List<String> systemIds = null;
        if (StringUtils.hasLength(authSystem)) {
            String[] split = authSystem.split(",");
            systemIds = Arrays.asList(split);
        }
        if (CollectionUtils.isEmpty(systemIds) || !systemIds.contains(config.getSystemId() + "")) {
            return ResponseResult.error("您没有操作此系统的权限");
        }
        service.saveData(config);
        return ResponseResult.success(config);
    }

    @GetMapping("/page")
    @ApiOperation("分页获取列表")
    public ResponseResult<IPage<EntityConfig>> page(
            @ApiParam(value = "系统id", example = "1") @RequestParam Long systemId,
            @ApiParam(value = "当前页码", required = true, example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "每页大小", required = true, example = "10") @RequestParam Integer pageSize,
            @ApiParam(value = "系统权限ID") @RequestHeader(Constant.SYSTEM) String authSystem) {
        List<String> systemIds = null;
        if (StringUtils.hasLength(authSystem)) {
            String[] split = authSystem.split(",");
            systemIds = Arrays.asList(split);
        }
        if (CollectionUtils.isEmpty(systemIds) || !systemIds.contains(systemId + "")) {
            return ResponseResult.error("您没有操作此系统的权限");
        }
        return ResponseResult.success(service.getPage(systemId, pageNum, pageSize));
    }
}
